import { inject, reactive } from "vue";
import { isFunction, hasOwn } from "@vue/shared";
import { defaults } from "lodash-es";
import type { Node } from "@antv/x6";
import type { BaseChartNodeData } from "../factory/type";

type ReturnUseNodeData<T> = { node: Node; config: BaseChartNodeData["config"] & T };

export default function useNodeData<T extends Record<string, any>>(
	defaultConfigData?: ((node: Node) => T) | T
): ReturnUseNodeData<T> {
	const getNode = inject<() => Node>("getNode")!;
	const node = getNode();

	const data = isFunction(defaultConfigData)
		? defaultConfigData(node)
		: defaultConfigData ?? ({} as T);

	node.data ||= {};

	if (!hasOwn(node.data, "config")) {
		node.data.config = reactive(data);
	} else {
		node.data.config = reactive(defaults(node.data.config, data));
	}

	return { node, config: node.data.config };
}
